<?php
namespace app\api\core\wechat;

require_once (dirname(__DIR__).'/CreateUuid.php');

use Yii;
use \Cm;

class wxUser extends wechat
{
    //用户接口
    const USER_GET_URL='/user/get?';
    const USER_GET_URL_INFO='/user/info?access_token=';
    const USERS_GET_URL_INFO='/user/info/batchget?access_token=';

    /**
     * 初始化操作
     * wecaht constructor.
     */
    public function __construct()
    {
        return parent::__construct();
    }
    /**
     * 批量获取关注用户列表
     * @param $authorizer_appid:微信公总号、appid
     * @param $next_openid：最后一个用户的openid
     * @return bool|mixed
     */
    public function getUserList ($authorizer_appid, $next_openid='')
    {

        if (!$this->getAuthInfo($authorizer_appid)) {
            return false;
        }

        $authorizer_access_token = $this->getAuthorizerAccessToken($authorizer_appid);
        if (!$authorizer_access_token) {
            return false;
        }
        if($next_openid) {
            $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$authorizer_access_token.'&next_openid='.$next_openid);
        } else {
            $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$authorizer_access_token);
        }
        if ($result) {
            $json = json_decode($result,true);
            if (isset($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }

            $nextOpenid = $json['next_openid'];
            if (!isset($json['data']['openid'])) {
                return false;
            }
            $data = $json['data']['openid'];

            $total = (int)$json['total'];#粉丝总人数
            $count = (int)$json['count'];#当前粉丝数

            $userCount = count($data);


            //批量获取用户数据
            if ($userCount < 100) {
                return $this->getBatchUsersInfo($authorizer_appid, $data);
            } else {
                $i = (int)ceil($userCount/100);
                $k = 0;
                while ($k < $i) {
                    $star_index = $k * 100;

                    $temp = array_slice($data, $star_index, 100);

                    $this->getBatchUsersInfo($authorizer_appid, $temp, $k);
                    $k++;
                }
            }

            //一直取数据
            if (!empty($nextOpenid)) {
                return $this->getUserList($authorizer_appid, $nextOpenid);
            }
        }
        return true;
    }

    /**
     * 获取单个用户信息
     * @param $authorizer_appid
     * @param $openid
     * @param bool $insert
     * @return array|bool|false
     */
    public function getUserInfo($authorizer_appid, $openid, $insert=false)
    {
        if (!$this->getAuthInfo($authorizer_appid)) {

            return false;
        }


        $authorizer_access_token = $this->getAuthorizerAccessToken($authorizer_appid);

        if (!$authorizer_access_token) {
            return false;
        }

        $sql = "SELECT company_id FROM `scrm_weixin_company_account` WHERE wx_account_id='{$this->wx_app_data_id}'";
        $realation = Cm::$db->one($sql);

        YII_DEBUG && $this->logResult('/realation.log','转换成json：'.json_encode($realation)."sql:$sql");
        $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL_INFO.$authorizer_access_token.'&openid='.$openid);
        if ($result) {
            $json = json_decode($result,true);
            if (isset($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                $this->error = $json['errmsg'];
                return false;
            }
            if ($insert) {
                $data = Cm::$db->one("select id from `scrm_weixin_customer` WHERE openid='{$openid}' and wx_account_id='{$this->wx_app_data_id }'");
                if ((int)$json['subscribe']) {
                    $user = [
                        'openid'=>$json['openid'],
                        'unionid'=>isset($json['unionid']) ? $json['unionid'] : '',
                        'subscribe'=>date('Y-m-d', $json['subscribe_time']),
                        'unsubscribe'=>'',
                        'status'=>(int)$json['subscribe'],
                        'nick_name'=>$this->filterEmoji($json['nickname']),
                        'sex'=>(int)$json['sex'],
                        'city'=>$json['city'],
                        'province'=>$json['province'],
                        'country'=>$json['country'],
                        'headimgurl'=>$json['headimgurl'],
                        //'last_time'=>$json[''],
                        //'qrcode'=>$json[''],
                        'groupid'=>$json['groupid'],
                        'remark'=>$json['remark'],
                        'tagid_list'=>!empty($json['tagid_list']) ? implode(',', $json['tagid_list']) : '',
                        'subscribe_scene'=>$json['subscribe_scene'],
                        'subscribe_scene_type'=>self::getSubscribeScene($json['subscribe_scene']),
                        'company_id'=>$this->company_id,
                        'qr_scene'=>$json['qr_scene'],
                        'qr_scene_str'=>$json['qr_scene_str'],

                    ];
                } else {
                    $user = [
                        'openid'=>$json['openid'],
                        'status'=>0,
                    ];
                }

                if ($realation && !empty($realation['company_id'])) {
                    $user['company_id']  = $realation['company_id'];
                } else {
                    $user['company_id'] = $this->company_id;
                }

                if (!$data) {
                    $user['date_added']=date('Y-m-d H:i:s');
                    $user['wx_account_id']=$this->wx_app_data_id ;
                    $user['id']=(new \app\api\core\CreateUuid())->toString();

                    Cm::$db->insert('scrm_weixin_customer', $user);
                } else {
                    Cm::$db->update('scrm_weixin_customer', $user, "openid='{$openid}' and wx_account_id='{$this->wx_app_data_id }'");
                }
            }

            $resultData = Cm::$db->one("select * from `scrm_weixin_customer` WHERE openid='{$openid}' and wx_account_id='{$this->wx_app_data_id }'");
            return true;
        }
        $this->error = !empty($this->error) ? $this->error : '获取用户信失败!';
        return false;
    }

    /**
     * 处理微信昵称emoji方法
     * @param $str
     * @return mixed
     */
    public function filterEmoji($str)
    {
        $str = preg_replace_callback( '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

        return $str;
    }

    /**
     * 获取批量用户信息
     * @param $authorizer_appid
     * @param array $openids
     * @return bool
     */
    public function getBatchUsersInfo($authorizer_appid, $openids = [], $i=0)
    {
        $authorizer_access_token = $this->getAuthorizerAccessToken($authorizer_appid);
        if (!$authorizer_access_token) {
            return false;
        }

        $realation = Cm::$db->one("SELECT company_id FROM `scrm_weixin_company_account` WHERE wx_account_id='{$this->wx_app_data_id}'");

        $list = [];
        if (is_array($openids) && !empty($openids)) {
            foreach ($openids as $item) {
                $list[] = [
                    'lang'=>'zh_CN',
                    'openid'=>$item,
                ];
            }
            $jsonParams = json_encode(['user_list'=>$list]);
            $result = $this->http_post(self::API_URL_PREFIX.self::USERS_GET_URL_INFO.$authorizer_access_token, $jsonParams);

            if ($result) {
                $json = json_decode($result,true);
                if (isset($json['errcode'])) {
                    $this->errCode = $json['errcode'];
                    $this->errMsg = $json['errmsg'];
                    $this->error = $json['errmsg'];
                    return false;
                }

                $data = isset($json['user_info_list']) ? $json['user_info_list'] : [];
                if (!empty($data)) {
                    foreach ($data as $item) {
                        $resultData = Cm::$db->one("select id from `scrm_weixin_customer` WHERE openid='{$item['openid']}' and wx_account_id='{$this->wx_app_data_id }'");

                        if ((int)$item['subscribe'] > 0) {
                            $user = [
                                'openid'=>$item['openid'],
                                'unionid'=>isset($item['unionid']) ? $item['unionid'] : '',
                                'subscribe'=>date('Y-m-d H:i:s', $item['subscribe_time']),
                                //'unsubscribe'=>0,
                                'status'=>(int)$item['subscribe'],
                                'nick_name'=>$this->filterEmoji($item['nickname']),
                                'sex'=>(int)$item['sex'],
                                'city'=>$item['city'],
                                'province'=>$item['province'],
                                'country'=>$item['country'],
                                'headimgurl'=>$item['headimgurl'],
                                //'last_time'=>$item[''],
                                //'qrcode'=>$item[''],
                                'groupid'=>$item['groupid'],
                                'remark'=>$item['remark'],
                                'tagid_list'=>!empty($item['tagid_list']) ? implode(',', $item['tagid_list']) : '',
                                'subscribe_scene'=>$item['subscribe_scene'],
                                'subscribe_scene_type'=>self::getSubscribeScene($item['subscribe_scene']),
                                'company_id'=>$this->company_id,
                                'qr_scene'=>$item['qr_scene'],
                                'qr_scene_str'=>$item['qr_scene_str'],


                            ];
                        } else {
                            $user = [
                                'openid'=>$item['openid'],
                                'status'=>0,
                            ];
                        }
                        if ($realation && !empty($realation['company_id'])) {
                            $user['company_id']  = $realation['company_id'];
                        } else {
                            $user['company_id'] = $this->company_id;
                        }
                        if (!$resultData) {
                            $user['date_added']=date('Y-m-d H:i:s');
                            $user['wx_account_id']=$this->wx_app_data_id ;
                            $user['id']=(new \app\api\core\CreateUuid())->toString();
                            Cm::$db->insert('scrm_weixin_customer', $user);
                        } else {
                            Cm::$db->update('scrm_weixin_customer', $user, "openid='{$item['openid']}' and wx_account_id='{$this->wx_app_data_id}'");
                        }
                    }
                }

            }
        }
        return true;
    }

    /**
     * 获取用户关注公总号来源
     * @param $subscribe_scene
     * @return int
     */
    public static function getSubscribeScene($subscribe_scene)
    {
        switch (trim($subscribe_scene)) {
            case 'ADD_SCENE_SEARCH':#公众号搜索
                $type = 0;
                break;
            case 'ADD_SCENE_ACCOUNT_MIGRATION':# 公众号迁移
                $type = 1;
                break;
            case 'ADD_SCENE_PROFILE_CARD':#名片分享
                $type = 2;
                break;
            case 'ADD_SCENEPROFILE_LINK':#图文页内名称点击
                $type = 3;
                break;
            case 'ADD_SCENE_QR_CODE':#扫描二维码
                $type = 4;
                break;
            case 'ADD_SCENE_PROFILE_ITEM':#图文页右上角菜单
                $type = 5;
                break;
            case 'ADD_SCENE_PAID':#支付后关注
                $type = 6;
                break;
            default:
                $type = 7;
                break;
        }
        return $type;
    }

}